package com.eryos.android.cigarettecounter;

/**
 * Project :  CigaretteCounter
 * Author :   Olivier Combe 
 * URL :      http://eryos.fr/CigaretteCounter/
 *
 * Copyright (C) 2011 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

import java.io.IOException;
import java.util.ArrayList;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;

import com.eryos.android.cigarettecounter.io.DataExporter;
import com.eryos.android.cigarettecounter.io.DataImporter;
import com.eryos.android.cigarettecounter.io.Preferences;

public class ConfigActivity extends RootActivity {

	int boxSize = -1;
	float boxPrice = -1l;
	
	Button cleanDataButton; 
	Button insertButton; 
	Button exportButton; 
	Button importButton; 
	Button invalidDateButton; 
	Button validButton; 
	DatePicker invalidDatePicker;
	EditText priceInputField;
	
	Spinner boxSpinner;
	ArrayAdapter<CharSequence> adapter;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public void initUI(){    	
        setContentView(R.layout.config);

        cleanDataButton 	= (Button) findViewById(R.id.config_button_delete);
        insertButton 		= (Button) findViewById(R.id.config_button_insert);
        invalidDateButton 	= (Button) findViewById(R.id.config_button_invalid);
        invalidDatePicker 	= (DatePicker) findViewById(R.id.config_invalid_date_picker);
        exportButton 		= (Button) findViewById(R.id.config_export_button);
        validButton 		= (Button) findViewById(R.id.config_valid_button);
        importButton 		= (Button) findViewById(R.id.config_import_button);
        Spinner boxSpinner 	= (Spinner) findViewById(R.id.config_size_value);
        priceInputField		= (EditText) findViewById(R.id.config_price_edittext);
        //priceInputField.setInputType(NUMERIC);
        
        adapter = ArrayAdapter.createFromResource( this, R.array.sizes_array, android.R.layout.simple_spinner_item);
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    boxSpinner.setAdapter(adapter);
	    
	    boxSpinner.setOnItemSelectedListener(new OnItemSelectedListener(){
			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { 
		    	String res = parent.getItemAtPosition(pos).toString(); 
		    	boxSize = new Integer(res);
			} 
		 
		    public void onNothingSelected(AdapterView<?> parent) { 
		      // Do nothing. 
		    } 
		});            

        validButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	showWaitingMessage();
            	saveConfig();
            }
        });
        
        cleanDataButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	showWaitingMessage();
            	db.open();
            	deleteData();
            }
        });
        
        exportButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	showWaitingMessage();
            	db.open();
            	exportData();
            }
        });
        
        importButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	showWaitingMessage();
            	db.open();
            	importData();
            }
        });

        insertButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	showWaitingMessage();
            	db.open();
            	insertData();
            }
        });
        
        invalidDateButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	showWaitingMessage();
            	db.open();
            	invalidDate();
            }
        });
    }
    
    public void initValues(){    	

    	Preferences pref = new Preferences(getSharedPreferences(PREFS_NAME, 0));
    	pref.readParamFromFile();
    	boxPrice = pref.getBoxPrice();
    	boxSize = pref.getBoxSize();
    	
    	int position = 0;
    	ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource( this, R.array.sizes_array, android.R.layout.simple_spinner_item);
	    
    	for ( int i = 0 ; i < adapter.getCount(); i++ ){
    		int valueList = Integer.parseInt(adapter.getItem(i).toString());
    		if ( valueList == boxSize  )
    			position = i;
    	}
    	if ( boxPrice != -1l )
    		priceInputField.setText(boxPrice+"");
    	
    	if ( boxSize != -1 && boxSpinner != 
    		
    		null)
    		boxSpinner.setSelection(position);
    }
    
    /**
     * Save the current price and box size values
     */
    public void saveConfig(){
    	Preferences pref = new Preferences(getSharedPreferences(PREFS_NAME, 0));
    	
    	pref.setBoxSize(boxSize);
    	Float boxPrice = new Float(priceInputField.getText().toString());
    	pref.setBoxPrice(boxPrice);

    	float cigPrice = boxPrice / boxSize;
    	System.out.println(cigPrice);
    	pref.setCigarettePrice(cigPrice);

    	pref.storeParamToFile();
    	
    	hideWaitingMessage(R.string.config_valid_OK);
    }
    
    /**
     * Delete all data from DB
     */
    public void deleteData(){
    	db.deleteAll();

    	hideWaitingMessage(R.string.config_delete_OK);
    }
    
    /**
     * Insert random data for the last 6 months
     */
    public void insertData(){
    	db.initialLoad();
    	
    	hideWaitingMessage(R.string.config_insert_OK);
    }
    
    /**
     * Invalid the date selected with the date picker
     */
    public void invalidDate(){
    	int day = invalidDatePicker.getDayOfMonth();
    	int month = invalidDatePicker.getMonth()+1;
    	int year = invalidDatePicker.getYear();

    	db.invalidDate(day, month, year);
    	
    	hideWaitingMessage(R.string.config_invalid_OK);
    }

    
    /**
     * Export data to SD card ( Public Downloads folder )
     */
    public void exportData(){
    	DataExporter export = new DataExporter(SDCARD_NAME);

    	try {
			if ( export.openStream() ){

				ArrayList<String> data = db.exportData();
				
				for (String line : data ){
					export.writeDataToExternalFile(line+"\n");
			    	
				}
				export.closeStream();
			}
		} catch (IOException e) {
			e.printStackTrace();
			hideWaitingMessage(R.string.config_export_NOK);
		}

    	hideWaitingMessage(R.string.config_export_OK);
    }
    
    /**
     * Import data from SD Card file
     */
    public void importData(){
    	DataImporter importer = new DataImporter(SDCARD_NAME);
    	
    	try {
			if ( importer.openStream() ){
				
				ArrayList<String> data = importer.readDataFromExternalFile();
				db.importData(data);
							    
				importer.closeStream();
			}
		} catch (IOException e) {
			e.printStackTrace();
			hideWaitingMessage(R.string.config_import_NOK);
		}
		
		hideWaitingMessage(R.string.config_import_OK);
    }

}
